<template>
	<view id="edit_add_rws">
		<view class="status_bar">
			<!-- 这里是状态栏 -->
		</view>
		<view class="body">
			<view class="title">{{title}}</view>
			<view class="top">
				<button @click="formSubmit" style="margin: 0;" size="mini">{{$t('global.button.sure')}}</button>
			</view>
			<scroll-view class="form_warpper" scroll-y="true">

				<uni-forms validateTrigger="bind" :modelValue="formdata" :rules="rules" ref="runewordsForm">
					<uni-forms-item name="name" :label="$t('rune.runewords.form.name.label')">
						<uni-easyinput :clearable="true" type="text" v-model="formdata.name"
							:placeholder="$t('rune.runewords.form.name.placeholder')" />
					</uni-forms-item>

					<uni-forms-item name="runes" :label="$t('rune.runewords.form.runes.label')">
						<uni-easyinput :clearable="true" type="text" v-model="formdata.runes"
							:placeholder="$t('rune.runewords.form.runes.placeholder')" />
					</uni-forms-item>
					<view class="run-img-list">
						<template v-for="(rune,index) in curInputRune">
							<view class="img-box" :key="'show-rune'+ index">
								<image :src="'/static/img' + rune.src" mode="aspectFit"></image>
							</view>
						</template>
					</view>

					<uni-forms-item name="effect" :label="$t('rune.runewords.form.effect.label')">
						<uni-easyinput :clearable="true" type="textarea" v-model="formdata.effect"
							:placeholder="$t('rune.runewords.form.effect.placeholder')" />
					</uni-forms-item>

					<uni-forms-item name="unlock" :label="$t('rune.runewords.form.unlock.label')">
						<uni-data-checkbox class="unlock_checkbox" v-model="formdata.unlock"
							:localdata="unloceStatus"></uni-data-checkbox>
					</uni-forms-item>


				</uni-forms>
			</scroll-view>
		</view>

	</view>
</template>

<script>
	/**
	 *  uni_forms 文档 https://uniapp.dcloud.net.cn/component/uniui/uni-forms.html#%E4%BB%8B%E7%BB%8D
	 * uni_modules 官方组件所有需自己导入列表:  https://uniapp.dcloud.net.cn/component/uniui/quickstart.html#%E9%80%9A%E8%BF%87-uni-modules-%E5%8D%95%E7%8B%AC%E5%AE%89%E8%A3%85%E7%BB%84%E4%BB%B6
	 * 	uni_forms： https://ext.dcloud.net.cn/plugin?name=uni-forms
	 *  uni-easyinput https://ext.dcloud.net.cn/plugin?name=uni-easyinput
	 *  uni-data-checkbox https://ext.dcloud.net.cn/plugin?id=3456
	 * */
	import $validate_ from '@/utils/validate.js';
	import $cst_ from '@/utils/constant.js'
	import $utils_ from '@/utils/common.js'


	import RUNEWORDS_DATA from "@/data/runewords.js";
	import RUNES_DATA from "@/data/runes.js";
	export default {
		data() {
			const _this = this;
			return {
				title: _this.$t("rune.runewords.form.title.add_word"),
				formType: $cst_.OPS.ADD,
				curInputRune: [],
				original_data: {},
				formdata: {
					name: '',
					runes: '',
					effect: '',
					unlock: 1,
				},
				unloceStatus: [{
					value: 0,
					text: _this.$t("rune.runewords.form.unlock.labels[0]")
				}, {
					value: 1,
					text: _this.$t("rune.runewords.form.unlock.labels[1]")
				}],
				rules: {
					name: {
						rules: [{
								required: true,
								errorMessage: _this.$t('rune.runewords.form.name.valid.required'),
								// validateTrigger: 'blur',
								// validateTrigger: 'bind',
								// validateTrigger: 'submit',
							},
							{
								validateFunction: (rule, value, data, callback) => {
									if ($validate_.reg.backspace_.test(value)) {
										return callback(_this.$t('rune.runewords.form.name.valid.required'));
									} else {
										callback();
									}
								}
							},
							{
								maxLength: 24,
								errorMessage: _this.$t('global.validate.maxLength24'),

							}
						],
					},
					runes: {
						rules: [{
								required: true,
								errorMessage: _this.$t('rune.runewords.form.runes.valid.required'),
							},
							{
								validateFunction: (rule, value, data, callback) => {
									let reg1 = /^[a-zA-Z]+(,[a-zA-Z]+)*$/; // 字符校验
									let reg2 = /^[a-zA-Z]{1,5}(,[a-zA-Z]{1,5})*$/; // 符石名称校验
									let reg3 = /^[a-zA-Z]{1,5}(,[a-zA-Z]{1,5}){1,2}$/; // 符石数量2,3

									// console.log("111", value);
									if (!reg1.test(value)) {
										// console.log("1123",value);
										return callback(_this.$t('rune.runewords.form.runes.valid.alphabet'));
									} else if (!reg2.test(value)) {
										return callback(_this.$t(
											'rune.runewords.form.runes.valid.rune_name_length'));
									} else {
										// console.log("222", value);
										let runes = value.split(",");


										if (runes.length > 1) {
											// 符石重复校验
											for (let i = 0; i < runes.length - 1; i++) {
												for (let j = i + 1; j < runes.length; j++) {
													// console.log(i, j, runes[i], runes[j], runes[i].toUpperCase(), runes[j].toUpperCase());
													if ((runes[i].toUpperCase()) === (runes[j].toUpperCase())) {
														return callback(runes[j] + " " + _this.$t(
															'rune.runewords.form.runes.valid.rune_repeat'));
													}
												}
											}
										}


										// console.log("223", value);

										let runes_ = []; // 展示符石图片

										let name_orders = []; // 用于符文是否已存在判断
										// 符石存在判断
										for (let i = 0; i < runes.length; i++) {
											let name = runes[i].toUpperCase();
											// if (!RUNES_DATA.some(el => el.name === name)) {
											let rune = _this.runesMap.get(name);
											if (!rune) {
												return callback(runes[i] + " " + _this.$t(
													'rune.runewords.form.runes.valid.abset'));
											}

											name_orders.push(rune.order);
											runes_.push(rune);
										}

										// 展示符石图片

										_this.$nextTick(() => {
											_this.curInputRune = runes_;
										});

										// console.log("224", value);
										// 符石数量2,3判断
										if (!reg3.test(value)) {
											return callback(_this.$t('rune.runewords.form.runes.valid.rune_num'));
										}

										// 符文是否已存在


										name_orders.sort((a, b) => a - b);



										for (let j = 0; j < _this.user_runewords.length; j++) {
											let ele = _this.user_runewords[j];
											if (!ele.known) {
												// console.log("skip known false");
												continue;
											}
											// console.log(_this.formType, $cst_.OPS.SET,_this.original_data.order,ele.order);
											if (_this.formType === $cst_.OPS.SET && _this.original_data.order ===
												ele.order) {
												// console.log("skip self");
												continue;
											}
											// console.log("x2x4");
											if (ele.runes_o.toString() === name_orders.toString()) {
												return callback(_this.$t(
													'rune.runewords.form.runes.valid.word_exist'));
											}
										}


										// 再去exclusion中判断是否存在
										for (let i = 0; i < _this.exclusion.length; i++) {
											let ele = _this.exclusion[i];
											if (ele.runes_o.toString() === name_orders.toString()) {
												return callback(_this.$t(
													'rune.runewords.form.runes.valid.word_exist_in_exclusion'
												));
											}

										}
										// console.log("x2x3");










										// console.log("411");

									}
									// console.log("333");
									callback();
								}
							},



						],
					},
					effect: {
						rules: [{
								required: true,
								errorMessage: _this.$t('rune.runewords.form.effect.valid.required'),
								// validateTrigger: 'blur',
								// validateTrigger: 'bind',
								// validateTrigger: 'submit',
							},
							{
								validateFunction: (rule, value, data, callback) => {
									if ($validate_.reg.backspace_.test(value)) {
										return callback(_this.$t('rune.runewords.form.effect.valid.required'));
									} else {
										callback();
									}
								}
							},
							{
								maxLength: 80,
								errorMessage: _this.$t('global.validate.maxLength80'),

							}
						],
					},


				},





				runes: RUNES_DATA,

				/**@todo 应该使用vux或者全局变量*/
				user_runewords: [],
				exclusion: [],

				/**@todo 应该使用vux或者全局变量*/
				runesMap: new Map(),
				runewordsMap: new Map(),
			};
		},


		watch: {
			["formdata.runes"](newVal, oldVal) {
				// console.log(newVal, oldVal);
				if (newVal === "") {
					this.$nextTick(() => {
						this.curInputRune = [];
					})
				}
			}
		},

		created() {
			console.log('执行了created。。。');
			const _this = this;

			_this.runes.forEach((val) => {
				this.runesMap.set(val.name, val);
			});

			_this.user_runewords = _this.getUserRunewords();
			_this.exclusion = _this.getExclusion();
			// console.log(_this.user_runewords)

			// _this.$utils_.testJSONPS();
			// uni.$once("test", (res) => {
			// 	console.log("res", res);
			// });
		},
		onLoad(option) {
			const _this = this;
			console.log('执行了onLoad...', option);
			const eventChannel = _this.getOpenerEventChannel();
			// 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
			eventChannel.once('acceptDataFromOpenerPage', (res) => {
				console.log("acceptDataFromOpenerPage", res);
				if (res.type == $cst_.OPS.ADD) {
					_this.formType = $cst_.OPS.ADD;
					_this.title = _this.$t("rune.runewords.form.title.add_word");
				} else if (res.type == $cst_.OPS.SET) {

					_this.formType = $cst_.OPS.SET;
					_this.title = _this.$t("rune.runewords.form.title.set_word");

					_this.original_data = res.data;

					_this.formdata.name = res.data.name;
					_this.formdata.runes = res.data.runes.toString();
					_this.formdata.effect = res.data.effect;
					_this.formdata.unlock = res.data.unlock ? 1 : 0;

					_this.$nextTick(() => {
						if (res.data.runes_.length) {

							_this.curInputRune = $utils_.JSONParse($utils_.JSONStringify(res.data.runes_));
						} else {
							_this.curInputRune = [];
						}
					});
				}

			});
			// 获取所有任务数据上级任务用

			// uni.navigateBack({
			// 	success(res) {
			// 		uni.showToast({
			// 			title: _this.$t('proManager.taskManager.note.fetch_data_error'),
			// 			image: '/static/img/toast/failure.png',
			// 			duration: 2000
			// 		});
			// 	}
			// });

			// uni.navigateBack({
			// 	success(res) {
			// 		uni.showToast({
			// 			title: _this.$t('proManager.taskManager.note.fetch_data_error'),
			// 			image: '/static/img/toast/failure.png',
			// 			duration: 2000
			// 		});
			// 	}
			// });
		},
		methods: {

			/**
			 * @description 将获取到的用户userdata runewords数据加工
			 * @param {RuneWord[]} userRunewords 本地存储的用户数据
			 * @return {{...RuneWord, runes_: Rune[], runes_o: number[]}[]}
			 * @todo 转成全局方法或使用vuex
			 * */
			userRunewordsProcesser(userRunewords) {
				const _this = this;
				let data = [];

				userRunewords.forEach((val) => {
					if (!val.del) {
						// 删除的数据不显示
						let obj = {
							...val
						};
						if (obj.runes.length) {

							let runes_ = []; // runes_存放rune数据
							let runes_o = []; // runes_存放rune对应order，！！！重新按大小排序
							for (let i = 0; i < val.runes.length; i++) {
								let name = val.runes[i];

								let rune = _this.runesMap.get(name);
								if (rune) {
									runes_.push(rune);
									runes_o.push(rune.order);
								} else {
									console.warn(`未找到name为${name}的rune`);
								}
							}
							runes_o.sort((a, b) => (a - b)); // !!! 重新排序，计算所有组合就是按照runes默认顺序来的
							obj.runes_ = runes_;
							obj.runes_o = runes_o;
						} else {
							obj.runes_ = [];
							obj.runes_o = [];
						}
						data.push(obj);
					}
				});

				// console.log(data);

				/**@type {{...RuneWord, runes_: Rune[], runes_o: number[]}[]} */
				return data;
			},
			// 获取userdata : runewords
			getUserRunewords() {
				const _this = this;
				try {
					// throw new Error("test");
					let val = uni.getStorageSync($cst_.KEY_OF_RUNEWORDS);

					// console.log("val：", val);
					if (val) {
						let data = _this.$utils_.JSONParse(val);
						let res = _this.userRunewordsProcesser(data);

						res.forEach((val) => {
							if (val.runes_o.length) {
								_this.runewordsMap.set(val.runes_o.toString(), val);
							}
						});
						// console.log(_this.runewordsMap);

						return res;

					} else {
						// 按道理添加编辑不可能走这边
						console.error("userdata runewords不存在");
						return [];
					}
				} catch (e) {
					console.error(e);
					return [];
				}
			},

			/**
			 * @description 获取exclusion
			 * @to vuex or globaldata
			 * */
			getExclusion() {
				const _this = this;
				try {
					// throw new Error("test");
					let val = uni.getStorageSync(_this.$cst_.KEY_EXCLUSION_OF_RUNEWORDS);
					console.log(val);
					if (val) {
						return $utils_.JSONParse(val);

					} else {
						console.log("EXCLUSION init");
						uni.setStorageSync(_this.$cst_.KEY_EXCLUSION_OF_RUNEWORDS, $utils_.JSONStringify([]));
						return [];
						// return [{
						// 	runes: [2, 1, 3],
						// 	runes_o: [1, 2, 3]
						// }, {
						// 	runes: [4, 7, 2],
						// 	runes_o: [2, 4, 7]
						// }];// 测试用
					}
				} catch (e) {
					console.error(e);
					return [];
				}
			},
			formSubmit: $utils_.debounce(function(el) {
				let _this = this;
				console.log("formSubmit");
				_this.$refs.runewordsForm.validate().then((res) => {
					// 成功返回，res 为表单数据
					// console.log(_this.$utils_.JSONStringify(_this.formdata), res);

					let user_runewords = _this.getUserRunewords();

					// console.log(_this.formType);
					if (_this.formType == $cst_.OPS.ADD) {
						try {
							// throw new Error("test");
							let obj = {
								order: user_runewords[user_runewords.length - 1].order + 1,
								name: _this.formdata.name,
								runes: _this.formdata.runes.toUpperCase().split(","),
								effect: _this.formdata.effect,
								effect_r: _this.formdata.effect, // @todo
								vars: [],
								known: true,
								unlock: !!_this.formdata.unlock,

								can_del: true, // 添加的数据可以被删除
								del: false,
							}

							user_runewords.push(obj);

							uni.setStorageSync($cst_.KEY_OF_RUNEWORDS,
								_this.$utils_.JSONStringify(user_runewords));

							console.log("添加成功");
							// 添加成功
							uni.navigateBack({
								success(res) {

									console.log("添加成功返回到上一页");
									// 刷新数据
									uni.showToast({
										title: _this.$t(
											'global.note.add_success'),
										image: '/static/img/toast/success.png',
										duration: 1000
									});
									uni.$emit('refresh');
								}
							});

						} catch (err) {
							console.error("add user runeword error:", err);
							uni.showToast({
								title: _this.$t(
									'global.note.add_failed'),
								image: '/static/img/toast/failure.png',
								duration: 2000
							});
						}

					} else if (_this.formType == $cst_.OPS.SET) {
						try {
							// throw new Error("test");

							let obj = {
								order: _this.original_data.order,
								name: _this.formdata.name,
								runes: _this.formdata.runes.toUpperCase().split(","),
								effect: _this.formdata.effect,
								effect_r: _this.original_data.effect_r, // @todo
								vars: _this.original_data.vars, // @todo
								known: true,
								unlock: !!_this.formdata.unlock,

								can_del: _this.original_data.can_del, // 
								del: false,
							};

							let i_ = user_runewords.findIndex(el => el.order === obj.order);
							// console.log("index:", i_);
							if (i_ === -1) {
								throw new Error(`修改数据时没找到要修改的数据 order:${obj.order}`);
							}

							user_runewords.splice(i_, 1, obj);

							uni.setStorageSync($cst_.KEY_OF_RUNEWORDS,
								_this.$utils_.JSONStringify(user_runewords));

							console.log("修改成功");
							// 修改成功
							uni.navigateBack({
								success(res) {

									console.log("修改成功返回到上一页");
									// 刷新数据
									uni.showToast({
										title: _this.$t(
											'global.note.set_success'),
										image: '/static/img/toast/success.png',
										duration: 1000
									});
									uni.$emit('refresh');
								}
							});


						} catch (err) {
							console.error("set user runeword error:", err);
							uni.showToast({
								title: _this.$t(
									'global.note.set_failed'),
								image: '/static/img/toast/failure.png',
								duration: 2000
							});
						}


					}

				}).catch((err) => {
					console.error(err);
					// 表单校验验失败，err 为具体错误信息
					// 其他逻辑处理
					uni.showToast({
						title: _this.$t('global.validate.error'),
						image: '/static/img/toast/error.png',
						duration: 500
					});
				});
			}, 500, true),



		}

	}
</script>
<style lang="scss">
	#edit_add_rws {
		height: 100%;
		background-color: rgb(28, 28, 28);
		// background-color: pink;

		.status_bar {
			position: fixed;
			top: 0;
			height: var(--status-bar-height);
			width: 100%;

			// background-color: blue;
			// background-color: #f5f5f5; // 防透视.data_area
			background-color: rgb(28, 28, 28);
			z-index: 99;
		}

		.body {
			height: calc(100% - var(--status-bar-height));
			padding-top: var(--status-bar-height);
			box-sizing: border-box;
			width: 100%;
			display: flex;
			flex-direction: column;

			.title {
				text-align: center;
				height: 60rpx;
				line-height: 60rpx;
				font-weight: 700;
				color: white;
			}


			.top {
				padding: 40rpx;
				display: flex;
				box-sizing: border-box;
				height: 80rpx;
				justify-content: flex-end;
				align-items: center;
				border-bottom: 2rpx dashed #d3d3d3;
			}

			.form_warpper {
				.uni-forms {
					// height: 10000rpx;
					padding: 10rpx 20rpx calc(var(--window-bottom) + 10rpx);
					box-sizing: border-box;

					.uni-forms-item {
						margin-bottom: 44rpx;
					}

					.unlock_checkbox {
						top: 50%;
						transform: translateY(-50%);
					}

					.run-img-list {
						display: flex;
						padding-left: 130rpx;
						// margin-bottom: 44rpx;
						margin-bottom: 20rpx;
						// background-color: yellow;
						box-sizing: border-box;
						width: 100%;
						height: 80rpx;

						.img-box {
							margin-right: 20rpx;
							height: 100%;
							width: 80rpx;

							uni-image {
								height: 100%;
								width: 100%;
							}
						}
					}
				}


				// 避免子元素撑起它
				flex: 1;
				min-height: 0;
				overflow: visible;
				// background-color: yellow;

			}
		}
	}
</style>